<?php

if(!defined('_BASE_')) {
define('_BASE_', 1);

include _ITSTOCK_LIB_DIR_.'common.inc.php';

define('_ITSTOCK_INSERT_', 1);
define('_ITSTOCK_UPDATE_', 2);
define('_ITSTOCK_DELETE_', 3);

function itstock_save(&$data) {
  foreach($data['data'] as $idx => &$struct){
    if ($struct['id'] === "") {
      $query[$idx] = itstock_prepare_insert($data, $idx);
    } else {
      $query[$idx] = itstock_prepare_update($data, $idx);
    }
  }
  return itstock_query($data, $query);
}

function itstock_prepare_insert(&$data, $idx) {
  $data['action'][$idx] = _ITSTOCK_INSERT_;
  foreach ($data['data'][$idx] as $key => $value) {
    if ($key !== "id") {
      isset($vals) ? $vals .= ',' : $vals = '';
      $vals .= (is_null($value)?'NULL':'\'' . itstock_db_insert_escape($value) . '\'');
    }
  }
  $cols = '`' . implode('`,`', array_keys($data['data'][$idx])) . '`';
  return "INSERT INTO " . $data['table'] . " ($cols) VALUES (null,$vals)";
}

function itstock_prepare_update(&$data, $idx) {
  $data['action'][$idx] = _ITSTOCK_UPDATE_;
  $data['data'][$idx]['id'] = itstock_decode($data['data'][$idx]['id']);
  foreach ($data['data'][$idx] as $key => $value) {
    isset($val) ? $val .= ',' : $val = '';
    $val .= '`' . $key . '`='.(is_null($value)?'NULL':'\'' . itstock_db_insert_escape($value) . '\'');
  }
  return "UPDATE " . $data['table'] . " SET $val WHERE id=" . $data['data'][$idx]['id'];
}

function itstock_query(&$data, $query) {
  itstock_db_connect($db);
  if (!itstock_db_error($db)) {
    foreach($query as $idx => &$qry) {
      if (!itstock_db_query($db, $qry)) {
        $data['msg'] = itstock_db_error($db);
        $data['errno'] = $db['errno'];
        return false;
      }
      if ($data['action'][$idx] === _ITSTOCK_INSERT_) {
        $data['data'][$idx]['id'] = itstock_db_last_id($db);
      }
    }
  } else {
    $data['msg'] = itstock_db_error($db);
    $data['errno'] = $db['errno'];
    return false;
  }
  return true;
}

function itstock_delete_internal(&$data) {
  $data['action'][0] = _ITSTOCK_DELETE_;
  $query[0] = "DELETE FROM " . $data['table'] . " WHERE id='" . $data['data'][0]['id'] . "'";
  return itstock_query($data, $query);
}

function itstock_delete(&$data) {
  $data['data'][0]['id'] = itstock_decode($data['data'][0]['id']);
  return itstock_delete_internal($data);
}

function itstock_decode_list_id(&$data) {
  if(array_key_exists('list_fields', $data)){
    foreach ($data['list_fields'] as &$field) {
      foreach($data['data'] as &$item) {
        $item[$field] = ((!isset($item[$field]) || $item[$field] === '')? null : itstock_decode($item[$field]));
      }
    }
  }
}

}
?>
